#include<stdio.h>
#include<string.h>

//PROCESS
#include<unistd.h>
#include<sys/types.h>

#include<sys/wait.h>
#include<stdlib.h>

//FIFO
#include<sys/stat.h>
#include<fcntl.h>

//MessageQueue
#include<sys/ipc.h>
#include<sys/msg.h>
#include "stdMsgQueue.h"

struct MessageQueue 
{
    key_t key;
    int msgid;
};
MsgQueue *InitMsgQueue(const char *_pathname, int _proj_id)
{
    MsgQueue *q=(MsgQueue*)malloc(sizeof(MsgQueue));
    if(q==NULL)
    {
        printf("InitMsgQueue malloc error!\n");
        return NULL;
    }
    key_t key=ftok("./",10);
    if(q->key<0)
    {
        perror("ftok: ");
        free(q);
        return NULL;
    }

    int msgid=msgget(q->key,IPC_CREAT|0777);
    if(q->msgid<0)
    {
        perror("msgget:");
        free(q);
        return NULL;
    }
    return q;
    
}

void MessageSend(MsgQueue *q, void *msg, size_t size)
{
    if(q=NULL)
    return;
    if(msgsnd(q->msgid,msg,size,0)==-1)
    {
        perror("mgsnd:");
        return ;
    }

}

void MessageRCV(MsgQueue *q, void *msg, size_t size, int type)
{
    if(q=NULL)
    return; 
    msgrcv(q->msgid,msg,size,type,0);
    MSG* msg1 = (MSG*)msg;
    printf("read from MessageSend : %s\n",msg1->content);

}

void ClearMsgQueue(MsgQueue *q)
{
    msgctl(q->msgid,IPC_RMID,NULL);
    free(q);
}
